#include "lsw100.h"
#include "RS232_DebugComm.h"
#include "serial.h"
#include "timer.h"

//#define RS232_DEBUG 1

static u8	m_Buf232Recv[RECV_BUF_SIZE];
static u8	m_CpuRecv[RECV_BUF_SIZE];


#define 	DEBUG_DATA_SRC  		CHAN_USART1 
#define     CPU_INTER_DATA_SRC	CHAN_USART2



typedef u32 (*F_Send_Data)(u8 * Data,u32 Len);


u32  Rs232_Send_Ack(TDataChan dest,u8* data, u32 len)
{
	u32 ret = 0;
	if(dest == CHAN_USART1){
		ret = usart_sendstring(1,data,len);
	}else if(dest == CHAN_USART2){
		ret = usart_sendstring(2,data,len);
	}
	return ret;
}
void CPU_Inter_RecvTask(void* tid, void* arg)
{

		
}
void Rs232RecvTask(void* tid, void* arg)
{
	int nRecv;
	//memset(m_Buf232Recv, 0, RECV_BUF_SIZE);
	nRecv = usart_getdatasize(1);
	if(nRecv >= sizeof(TCommMsg))
	{
		usart_getpacket(1,m_Buf232Recv,nRecv);
		ParseDebugCommMsg(DEBUG_DATA_SRC, m_Buf232Recv, nRecv, Rs232_Send_Ack);
	}
	nRecv = usart_getdatasize(2);
	if(nRecv >= sizeof(TCommMsg))
	{
		usart_getpacket(2,m_Buf232Recv,nRecv);
		ParseDebugCommMsg(CPU_INTER_DATA_SRC, m_Buf232Recv, nRecv, Rs232_Send_Ack);
	}
#if 0
	nRecv = usart_getpacket(1, m_Buf232Recv,RECV_BUF_SIZE);
	if(nRecv < 11) return; 
#ifdef RS232_DEBUG
	{
		u8 i = 0;
		for(i=0; i <nRecv;i++)
		{
			DebugPf("%x ",m_Buf232Recv[i]);
		}
		DebugPf("\r\nRecv=%d\r\n",nRecv);
	}
#endif
#endif	
	

}
static TSerialDesc uart2_desc={
	.baudrate = 115200,
	.databit  = 8,
	.stopbit  = 1
};
static int RS232_Debug_init()
{
	u8 ret = 0;

	struct TimerDevice* 	dev = NULL;
	struct TSerialDevice* 	uart_dev = NULL;
	DEBUG_FUNC();
	
	//OSTaskCreate(CPU_Inter_RecvTask, (void *)0, &CpuRecvStk[TASK_DEF_STK_SIZE - 1], TASK_PROI_CPU_INTER);
	dev = request_timer(1);
	if(dev == NULL) return 0;
	
	if( dev ){
		if(!create_timer(dev, 50*DELAY_MSECOND, Rs232RecvTask, NULL, LOOP))
			return 0;
	}
	if(!usart_open(2,&uart2_desc))
		return 0;
	
	return 1;
}
#if (RS232_DEBUG_MODULE_EN > 0)
module_initcall(RS232_Debug_init);
#endif

